package com.daocao.hua.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.activity.AboutActivity;
import com.daocao.hua.activity.V3XueXinFindByAccountActivity;
import com.daocao.hua.activity.V3XueXinForgetpassActivity;
import com.daocao.hua.activity.V3XueXinIdentityActivity;
import com.daocao.hua.activity.V3XueXinRegisterActivity;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.XueXinRegisterV3Bean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-7-10.
 */

public class V3XueXinRegisterFragment extends BaseFragment {
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_forget_account)
    TextView btnForgetAccount;
    @BindView(R.id.btn_forget_pass)
    TextView btnForgetPass;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    Unbinder unbinder;
    @BindView(R.id.edit_image_code)
    EditText editImageCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.code_view)
    LinearLayout codeView;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_xuexin_register_v3;
    }

    @Override
    protected void initView() {
        getChsiImgCodeInfo();
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
//                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText(getResources().getString(R.string.send_code_again));
//        btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }


    public void getChsiImgCodeInfo() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }

        Api.api_service.getXueXinCode().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    String imgStr = "";
                    String captcha = model.data;
                    if (captcha.contains(",")) {
                        imgStr = captcha.substring(captcha.indexOf(',') + 1);
                        imgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
                    } else imgCode.setImageDrawable(null);
                });
    }

    public void getXueXinRegisterSMSV3(String mobile, String captcha) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }
        ((V3XueXinIdentityActivity) getActivity()).loadingDialog.show();
        XueXinRegisterV3Bean bean = new XueXinRegisterV3Bean();
        bean.captcha = captcha;
        bean.mobile = mobile;
        Api.api_service.getXueXinRegisterSMSV3(bean).compose(RxLifeUtil.NocheckOn(getContext())).
                doFinally(() -> {
                    try {
                        ((V3XueXinIdentityActivity) getActivity()).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    if (model.getStatus() == 1) {
                        Intent intent = new Intent(getContext(), V3XueXinRegisterActivity.class);
                        intent.putExtra("mobile", mobile);
                        intent.putExtra("vcode", UI.toString(editCode));
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    } else {
                        ToastUtil.makeText(getContext(), model.getMsg());
                        getChsiImgCodeInfo();
                    }
                });
    }


    private boolean codeViewInputCheck() {
        if (TextUtils.isEmpty(UI.toString(editPhone))) {
            ToastUtil.makeText(getContext(), "手机号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editImageCode))) {
            ToastUtil.makeText(getContext(), "图片验证码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean codeViewInputCodeCheck() {
        if (TextUtils.isEmpty(UI.toString(editCode))) {
            ToastUtil.makeText(getContext(), "验证码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @OnTextChanged({R.id.edit_phone, R.id.edit_image_code, R.id.edit_code})
    void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editPhone)) &&
                !TextUtils.isEmpty(UI.toString(editImageCode)) &&
                !TextUtils.isEmpty(UI.toString(editImageCode))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbinder.unbind();
    }

    @OnClick({R.id.btn_send_code, R.id.btn_forget_account, R.id.btn_forget_pass, R.id.btn_submit, R.id.txt_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send_code:
                if (codeViewInputCheck()) {
                    try {
                        getXueXinRegisterSMSV3(UI.toString(editPhone), URLEncoder.encode(editImageCode.getText().toString(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_forget_account:
                Util.startActivity(getContext(), V3XueXinFindByAccountActivity.class);
                break;
            case R.id.btn_forget_pass:
                Util.startActivity(getContext(), V3XueXinForgetpassActivity.class);
                break;
            case R.id.btn_submit:
                if (codeViewInputCheck() && codeViewInputCodeCheck()) {
                    Intent intent = new Intent(getContext(), V3XueXinRegisterActivity.class);
                    intent.putExtra("vcode", UI.toString(editCode));
                    intent.putExtra("mobile", UI.toString(editPhone));
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                }
//                getXueXinRegisterV3();
                break;
            case R.id.txt_agree:
                Intent intent = new Intent(getContext(), AboutActivity.class);
                intent.putExtra("id", Const.ContractType.CHSI);
                intent.putExtra("type", 1);
                intent.putExtra("title", getResources().getString(R.string.service_contract_text2));
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }
}
